/*
 * @swipeImg 相册滑动
 */
/** 
var config = {
    domObj : ,//图片dom节点对象
    slideEndCB: //滑动结束回调函数
}
**/

function swipeImg (opts) {
    // this.oImgs = opts.oImgs;
    var defaultopts = {
        domObj:{
            $imgCon:$('#imgWrap'),
            $img:$('.j_img'),
            $slide:$('.j_slide'),
            $num:$('.j-index'),
            $desc:$('.j-desc-txt'),
            $title:$('.j-desc-tit'),
            $oIndexNav:$('.j_picnav'),
            $imgList:$('.j_show_list'),
            $imgWrap:$('.slide-wapper')
        },
        slideEndCB:function(){}
    }
    $.extend(this,defaultopts,opts);
    this.imgLen = this.domObj.$img.length;
    this.isFinished = false;  
    this.init(opts.imgCon);
}
swipeImg.prototype = {
    hasmove :  false,
    curIndex:0,
    init:function(obj){
        var that = this;
        var h = $(window).height();
        this.domObj.$imgCon.css({'height':h,'line-height':h+'px'});
        // load img
        // this.preloadImg()
        this.bindEvent();
        that.curIndex = this.initIndex -1 ;
        that.changeImg(that.curIndex);

    },
    preloadImg:function(index,direction){
        var that = this,
            $imgList = this.domObj.$img,
            max ,min,
            tempNum = 0;
            max = index+3 ;
        // if(direction=='next'){
        //     max = index+3 ;
        // }else if(direction == 'prev'){
        //     min = index-3 <0 ? 0 : index-3;
        // }

        $imgList.each(function(idx,node){
            if(tempNum < max){
                var img = new Image(),
                $_img = $(this).find('img');
                img.src =  $_img.attr('data-src');
                if( img.src != $_img.attr('src')){
                    img.onload = function(){
                        $_img.attr('src', img.src);
                        that.resetImg($_img);
                      
                    }
                }else{
                     that.resetImg($_img);
                }
               
                tempNum++ ;
            }
            else{
                return ;
            }
        })
       
    },
    resetImg:function(img){
        var scale = $(window).width()/$(window).height();
        var $_img = img;
        var imgW = $_img.get(0).naturalWidth;
        var imgH = $_img.get(0).naturalHeight;
     
        // console.log(imgW+'----'+imgH)
        $_img.removeClass('v_pic').removeClass('h_pic');

        if( (imgW/imgH) >= scale )
        {
            $_img.addClass('h_pic');
        }
        else{
            $_img.addClass('v_pic');
        }
    }
    ,
    resetHeight:function(){
        var that = this;
        var $_img = this.domObj.$img.eq(this.curIndex).find('img');
        // var img = new Image();
        // img.src =  $_img.attr('data-src');
        // console.log($_img )
        // img.onload = function(){
        //     $_img.attr('src', img.src);
        //    that.resetImg($_img);
        // }
          that.resetImg($_img);
      
    },
    bindEvent:function(){
        var that = this ;

        that.domObj.$imgCon.on("touchstart",function(e){that._touchstart(e);});
        that.domObj.$imgCon.on("touchmove",function(e){that._touchmove(e);});
        that.domObj.$imgCon.on("touchend touchcancel",function(e){that._touchend(e);});
        window.addEventListener('onorientationchange' in window ?
            'orientationchange' : 'resize', function () {
                setTimeout(function(){
                    that.resetHeight();
                },300);                     
        }, false);
    },
    _touchstart : function(e){  
        var allowY = this.allowScrollY(e);
       
        if( !allowY ){
           e.preventDefault();
        }
        if(e.touches && e.touches.length>1){
            //这里只允许单指操作
            return false;
        }
        this.startX = this.lastX = e.touches[0].pageX;
        this.startY = this.lastY = e.touches[0].pageY;
        this.hasmove = false;
            
    },
    _touchmove : function(e){
        // $(this).trigger('touchend');
        if(e.touches && e.touches.length>1){
            return false;
        }
        this.lastX = e.touches[0].pageX;
        this.lastY = e.touches[0].pageY;
    },
    allowScrollY : function(ev){
        var isAllow = false,
        target = ev.target,
        _$target = $(target);
        if(_$target.hasClass('j-desc-txt') || _$target.find('.j-desc-txt').length>0)
        {

            isAllow = true;
        }
        return isAllow;
      },
    _touchend : function(e){
        // e.preventDefault(); 
        var that = this ;
        var disX =  this.lastX  - this.startX ;
        var disY =  this.lastY  - this.startY ;
        var $slide = this.domObj.$slide;
        var len = $slide.length;

        if(Math.abs(disX) > 30 || Math.abs(disY) > 30 ){
            that.hasmove = true;
        }
        if(!that.hasmove && Math.abs(disX)==0 && Math.abs(disY) ==0){
            console.log(Math.abs(disX))
            var tagName = e.target.tagName.toLowerCase();
            if(tagName == 'img'){
                that.imgClickCb.call(this,e);
            }
            return ;
        }
        if(Math.abs(this.lastX - this.startX)>Math.abs(this.lastY - this.startY)){
            this.dragDirec = "x";
        }else{
            this.dragDirec = "y";
        }
        if(this.dragDirec == "x"){
            if(disX>0){
                // 左滑
                if(that.curIndex > 0){
                    that.curIndex = that.curIndex -1  ;
                       that.changeImg(that.curIndex,'prev');
                }
            }
            else{
                    
                    // 右滑
                    if(that.curIndex < len -1){
                        that.curIndex++ ;
                        that.changeImg(that.curIndex,'next');
                    }
                    else{
                        //go to next photo
                        that.nextCallback();
                    }

            }
            // that.changeImg(that.curIndex);

    }

    },
    getIndex:function(){
        return this.curIndex;
    },
    changeImg:function(index,direction){
        var that = this;
        var $slide = that.domObj.$slide;
        var $num =   that.domObj.$num;
        // console.log(that.curIndex)
        $num.html(index+1);
        // var startIdx = that.curIndex-2 <0 ? 0 : that.curIndex-2;
        that.curIndex = index;

        $slide.each(function(idx,node){
            if(idx == index){
                that.setPos($(node),0,2);
            }
            else if(idx == index-1){
                that.setPos($(node),-1,1);
            }  
            else if(idx == index-2){
                that.setPos($(node),-2,1);
            } 
            else if(idx == index+1){
                that.setPos($(node),1,1);
            }
            else if(idx == index+2){
                that.setPos($(node),2,1);
            }
            else{
                if(index > idx){
                    that.setPos($(node),2,1);
                }
                else{
                    that.setPos($(node),-2,1);
                }
                $(node).css('display','none')
            }
        })
        // console.log(index)
        that.changeDesc($slide,index);
        // 滑动结束回调函数
        if(that.slideEndCB){
            that.slideEndCB(index);
        }
       //  // 预加载图片
       that.preloadImg(index,direction);

    },
    changeDesc:function(slide,index){
        var that = this ;
        var $titDom = that.domObj.$title;
        var $descDom = that.domObj.$desc;
        var $curImgDom = slide.eq(index).find('img');
        var title = $curImgDom.attr('data-title');
        var desc = $curImgDom.attr('alt');
        $titDom.html(title);
        $descDom.html(desc);
    },
    setPos:function(node,scale,zindex){
        node.css({'-webkit-transform':"translate3d("+scale*100+"%,0,0)",'z-index':zindex,'display':'block'});
    }

}

// img
function autoImgPage(opts){
    var defaultopts= {
        domObj:{
            $imgCon:$('#imgWrap'),
            $img:$('.j_img'),
            $slide:$('.j_slide'),
            $num:$('.j-index'),
            $desc:$('.j-desc-txt'),
            $title:$('.j-desc-tit'),
            $oIndexNav:$('.j_picnav'),
            $imgList:$('.j_show_list'),
            $imgBrand:$('.j_show_list'),
            $imgWrap:$('.slide-wapper'),
            $oBackBtn:$('.back-btn')
        },
        pvUrl:'http://data.auto.sina.cn/ajx/carlibrary/pv?id=',
        pvFlagId:'',
        imgLen:0

    };
    $.extend(this,defaultopts,opts);
    this.init(this.oImgs);
}
autoImgPage.prototype = {
    init:function(oImgs){
        var that = this ;
        var wrap = this.domObj.$imgCon;
        that.posImg = new PosImg({
            $oBox   : {container:$('.j_l_container'),loading:$('.j_loading'),}, //容器、loading
            templet : '<div class=\"c_parent\" style=\"%%STYLE%%\" data-index=\"%%INDEX%%\"><img src=\"%%SRC%%\" alt=\"%%ALT%%\" /><p class="c_title">%%ALT%%</p></div>',   //插入节点的模板
            data    : []
            // callback : clickImgCB
        });
        that.imgLen = oImgs.length;
        that.posImg.init();
        that.imgSlide = new swipeImg({
            imgCon:'#imgWrap',
            oImgs:oImgs,
            pvUrl:that.pvUrl,
            initIndex:parseInt($('#photoindex').val()) || 0,
            imgClickCb:that.imgClickCb,
            slideEndCB:that.regardPv,
            nextCallback:that.nextCallback

        });

        that.domObj.$oIndexNav.on('click tap',function(){
            that.changeShow(true);
        });
        that.domObj.$oBackBtn.on('click tap',function(e){  
            e.preventDefault();
            var isOpenList = that.domObj.$oIndexNav.hasClass('cur'),
                href = '';
                console.log(isOpenList)
            if( isOpenList ){
                that.changeShow(true);
            }
            else{
                href = $(this).attr('href') || '/index';
                window.location.href = href;
            }
        });
     
    },
    nextCallback:function(index){
        var that = this,
            list = $('.j-brand-list'),
            imglen = that.imgLen,
            idx = list.find('.on').index(),
            brandLen = list.find('.item').length;
        if(idx+1 < brandLen){
            window.location.href = list.find('.item').eq(idx+1).attr('href');
        }
        else if(idx+1 ==brandLen ){
            window.location.href = list.find('.item').eq(0).attr('href');
        }

    },
    regardPv:function(index){
        var that = this;
         // 记录 pv

         var id= that.domObj.$img.eq(index).find('img').attr('data-id');
         if(that.pvFlagId =='' || that.pvFlagId != id){
            that.pvFlagId = id;
            $.post(that.pvUrl+id+"&g="+Math.random());
            if (typeof(SUDA) != 'undefined') {
              SUDA.log();
          }
      }
    },
    imgClickCb:function(e){
        var header = $('header');
        var desc = $('.img-desc');
        var footer = $('.brand-box');
        var wrap = this.domObj.$imgCon;
        var flag = wrap.attr('data-hide');
        if(flag == 'true'){
            header.show()
            desc.show()
            footer.show()
            $('.j-top-num').hide();
            wrap.attr('data-hide','false')
        }
        else{
            header.hide()
            desc.hide()
            footer.hide()
            $('.j-top-num').show();
            wrap.attr('data-hide','true')

        }
    },
    changeShow : function (isChange)
    {
        var that = this,
        isOpenList = that.domObj.$oIndexNav.hasClass('cur');
        if(isChange)
        {
            if( !isOpenList )
            {
                that.domObj.$oIndexNav.addClass('cur');

                that.posList();
                that.domObj.$imgWrap.hide()
                that.domObj.$imgList.show()
            }
            else{
                that.domObj.$oIndexNav.removeClass('cur');
                that.domObj.$imgWrap.show()
                that.domObj.$imgList.hide()
            }
        }
    },      
    posList : function(){
        var that = this,
        isOpenList = that.domObj.$oIndexNav.hasClass('cur');
        var clickImgCB = function(start){

            that.imgSlide.changeImg(start);
            that.changeShow(true);
        };
        if( isOpenList)
        {
            that.posImg.addItems(that.oImgs);
            that.posImg.setCallback(clickImgCB);
        }

    }
}
// page init
new autoImgPage({
    oImgs : getImgInfo()
});


// window.posImg = new PosImg({
//     $oBox   : {container:$('.j_l_container'),loading:$('.j_loading'),}, //容器、loading
//     templet : '<div class=\"c_parent\" style=\"%%STYLE%%\" data-index=\"%%INDEX%%\"><img src=\"%%SRC%%\" alt=\"%%ALT%%\" /><p class="c_title">%%ALT%%</p></div>',   //插入节点的模板
//     data    : []
//     // callback : clickImgCB
// });


// ---------------------------------------
    window.allowBodyScroll = function(){
        document.body.removeEventListener('touchmove', prevent, false);
    };
    window.forbidBodyScroll = function(){
     document.body.addEventListener('touchmove', prevent, false); 
    };
    window.prevent = function(e) {      
            //引导浮层存在时禁止页面滚动
            e.preventDefault();     
            return;
        };
    function getImgInfo(){
        var $img = $('.j_img'),
        oImgs = [];
        $img.each(function(){
            var $_this = $(this),
            tmpInfo = {},
            $_img = $_this.find('img');
            tmpInfo.src = $_img.data('smallsrc') || $_img.data('src') || $_img.attr('src'),
            tmpInfo.alt = $_img.attr('alt');
            tmpInfo.title = $_img.data('title') || $('#image_title').html() || $('title').html();
            oImgs.push(tmpInfo);
        });
        return oImgs;
    }


// ---------------------------------------




